﻿// <copyright file="TIProjectDefinesParser.cs" company="Horiba Medical">
//     Copyright (c) Horiba Medical. All rights reserved.
// </copyright>
// <summary>
//     Provides an project defines parser for TI project files.
// </summary>

namespace DoxyOutParser.CodeCheck
{
	using System;
	using System.Collections.Generic;
	using System.IO;

	/// <summary>
	/// Parses a TI project file to find the project defines specified within it.
	/// </summary>
	public class TIProjectDefinesParser : IProjectDefinesParser
	{
		/// <summary>
		/// The file which needs parsing.
		/// </summary>
		private string tiProjectFile;

		/// <summary>
		/// Initializes a new instance of the TIProjectDefinesParser class.
		/// </summary>
		/// <param name="projectFile">The TI project file which needs parsing.</param>
		public TIProjectDefinesParser(string projectFile)
		{
			// TODO Check the value of string and eventually check if exist or not.
			this.tiProjectFile = projectFile;
		}

		#region IProjectDefinesParser Members

		/// <summary>
		/// Returns a list of every project defines specified in a TI project file.
		/// </summary>
		/// <returns>The directory list.</returns>
		public string[] GetProjectDefinesTable()
		{
			// Using of StreamReader to parse the file
			StreamReader tiProjectStreamReader = new StreamReader(this.tiProjectFile);
			string line = tiProjectStreamReader.ReadLine();

			List<string> projectDefinesTempList = new List<string>();

			while (line != null)
			{
				// TODO FIXME for the moment the TI parsing take only project in debug mode.
				if (line.Contains("[\"Compiler\" Settings: \"SMC_DEV\"]"))
				{
					// Read Next Line
					line = tiProjectStreamReader.ReadLine();

					if (line.Contains("-d\""))
					{
						line = line.Substring(line.IndexOf("-d\"", StringComparison.Ordinal));
						do
						{
							int startIndex = line.IndexOf("-d\"", StringComparison.Ordinal);

							int endIndex = line.IndexOf("\"", startIndex + 3, StringComparison.Ordinal);
							if (endIndex != -1 && endIndex > startIndex)
							{
								string includeDir = line.Substring(startIndex + 3, (endIndex - startIndex - 3));
								projectDefinesTempList.Add(includeDir);
							}

							line = line.Substring(endIndex + 1);
						}
						while (line.Contains("-d\""));
						return projectDefinesTempList.ToArray();
					}
				}

				// Read Next Line
				line = tiProjectStreamReader.ReadLine();
			}

			return projectDefinesTempList.ToArray();
		}

		#endregion
	}
}
